package com.santu.edu.supporter.biz.good.service.impl;

import com.santu.edu.supporter.biz.good.dao.GoodDao;
import com.santu.edu.supporter.biz.good.pojo.dto.GoodDTO;
import com.santu.edu.supporter.biz.good.pojo.params.GoodAddParam;
import com.santu.edu.supporter.biz.good.pojo.params.GoodUpdateParam;
import com.santu.edu.supporter.biz.good.service.GoodService;
import com.santu.edu.supporter.biz.order.pojo.dto.GoodInfo;
import com.santu.edu.supporter.util.UuidUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author luoyaoqi
 * @createTime 2024/3/12
 * @description
 */
@Service
@RequiredArgsConstructor
public class GoodServiceImpl implements GoodService {

    private final GoodDao goodDao;


    @Override
    public Boolean addGood(GoodAddParam addParam) {
        String goodId = UuidUtils.getUuid(8);
        GoodDTO dto = GoodDTO.createItem(goodId, addParam);
        goodDao.addGood(dto);
        return true;
    }

    @Override
    public Boolean updateGood(GoodUpdateParam updateParam) {
        GoodDTO dto = GoodDTO.createItem(updateParam);
        goodDao.updateGood(dto);
        return true;
    }

    @Override
    public Boolean removeGood(String goodId) {
        goodDao.removeGood(goodId);
        return true;
    }

    @Override
    public List<GoodDTO> getGoodList(String categoryId) {
        return goodDao.getGoodList(categoryId);
    }

    @Override
    public Boolean lessGood(List<GoodInfo> goodInfoList) {
        Map<String, Integer> goodMap = goodInfoList.stream().collect(Collectors.toMap(GoodInfo::getGoodId, GoodInfo::getGoodNum));
        List<GoodDTO> goodList = goodDao.getGoodByIdList(new ArrayList<>(goodMap.keySet()));
        for (GoodDTO dto : goodList) {
            Integer lessNum = goodMap.get(dto.getGoodId());
            Integer totalNum = dto.getGoodNum();
            if (lessNum > totalNum) {
                return false;
            }
            goodDao.updateGoodNum(dto.getGoodId(), totalNum - lessNum);
        }
        return true;
    }
}
